<template>
  <doc-alert title="SaaS 多租户" url="https://doc.iocoder.cn/saas-tenant/" />
  <!-- 搜索 -->

  <ContentWrap>
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item :label="`商户类型`" prop="tenantType">
            <el-select v-model="queryParams.tenantType" :placeholder="`请选择商户类型`" clearable>
              <el-option
                v-for="dict in tenantTypeList"
                :key="dict.value"
                :label="dict.name"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item :label="`商户名`" prop="name">
            <el-input
              v-model="queryParams.name"
              :placeholder="`请输入商户名`"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="联系人" prop="contactName">
            <el-input
              v-model="queryParams.contactName"
              placeholder="请输入联系人"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="联系手机" prop="contactMobile">
            <el-input
              v-model="queryParams.contactMobile"
              placeholder="请输入联系手机"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item :label="`商户状态`" prop="status">
            <el-select v-model="queryParams.status" :placeholder="`请选择商户状态`" clearable>
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item :label="`商户来源`" prop="cropName">
            <el-input
              v-model="queryParams.cropName"
              :placeholder="`请输入商户名`"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="创建时间" prop="createTime">
            <el-date-picker
              v-model="queryParams.createTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="daterange"
              :shortcuts="defaultShortcuts"
              :disabled-date="disabledDate"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item>
            <el-button @click="handleQuery">
              <Icon icon="ep:search" class="mr-5px" />
              搜索
            </el-button>
            <el-button @click="resetQuery">
              <Icon icon="ep:refresh" class="mr-5px" />
              重置
            </el-button>
            <el-button
              type="primary"
              plain
              @click="openForm('create')"
              v-hasPermi="['system:tenant:create']"
            >
              <Icon icon="ep:plus" class="mr-5px" />
              新增
            </el-button>
            <el-button
              type="success"
              plain
              @click="handleExport"
              :loading="exportLoading"
              v-hasPermi="['system:tenant:export']"
            >
              <Icon icon="ep:download" class="mr-5px" />
              导出
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-tabs v-model="queryParams.tenantType" @tab-click="handleTabClick">
      <el-tab-pane
        v-for="item in tenantTypeList"
        :key="item.value"
        :label="item.name"
        :name="item.value"
      />
    </el-tabs>
    <el-scrollbar view-class="scrollbarClass">
      <div class="h-full flex flex-col justify-between" v-if="list.length > 0">
        <el-row :gutter="10" class="m-x-0!">
          <el-col
            :xs="24"
            :sm="24"
            :md="24"
            :lg="6"
            :xl="6"
            v-for="(item, index) in list"
            :key="index"
          >
            <ContentWrap
              class="cursor-pointer card-item bg-[var(--app-content-bg-color)]! dark:bg-[var(--el-bg-color)]!"
            >
              <div class="flex justify-between">
                <div class="flex">
                  <div>
                    <el-image
                      :preview-teleported="true"
                      :src="item.avatar"
                      class="w-[48px]! h-[48px]! m-r-10px rounded-4px align-middle"
                    />
                  </div>
                  <div class="custom-text-16">
                    <div class="font-bold">
                      {{ item.name }} <span class="pl-5px">{{ item.id }}</span>
                    </div>
                    <div class="mt-5px">
                      <el-text v-if="item.packageId === 0" type="danger">系统商户</el-text>
                      <template v-else>
                        <el-text>
                          {{ item.packageName }}
                        </el-text>
                      </template>
                    </div>
                  </div>
                </div>
                <div>
                  <DictTag :type="DICT_TYPE.COMMON_STATUS" :value="item.status" />
                </div>
              </div>
              <div class="flex custom-text-14 mt-10px">
                <el-text> 联系人：{{ item.contactName }} {{ item.contactMobile }}</el-text>
              </div>
              <div class="flex justify-between custom-text-14 mt-10px">
                <el-tooltip effect="light" placement="top">
                  <template #content>
                    <span v-for="(i, index) in item.tenantRespList" :key="i"
                      >{{ i.name }}
                      <span v-if="index != item.tenantRespList.length - 1">|</span></span
                    >
                  </template>
                  <el-text truncated>
                    关联商户：
                    <span v-for="(i, index) in item.tenantRespList" :key="i"
                      >{{ i.name }}
                      <span v-if="index != item.tenantRespList.length - 1">|</span></span
                    >
                  </el-text>
                </el-tooltip>
              </div>
              <div class="flex justify-between custom-text-14 mt-10px">
                <el-text> 过期时间：{{ formatDate(item.expireTime, 'YYYY-MM-DD') }} </el-text>
              </div>

              <div class="flex mt-10px items-center justify-between">
                <el-button
                  link
                  type="primary"
                  @click="openForm('update', item.id)"
                  v-hasPermi="['system:tenant:update']"
                >
                  编辑
                </el-button>
                <el-button link type="primary" @click="handleAuthorized(item)">
                  <!--  v-hasPermi="['system:tenant:update']" -->
                  关联商户
                </el-button>
                <!-- <el-button
                  link
                  type="danger"
                  @click="handleDelete(item.id)"
                  v-hasPermi="['system:tenant:delete']"
                >
                  删除
                </el-button> -->
                <el-button
                  link
                  type="warning"
                  @click="handleUpdatePassword(item)"
                  v-hasPermi="['system:tenant:admin:update-password']"
                >
                  重置密码
                </el-button>
              </div>
            </ContentWrap>
          </el-col>
        </el-row>
        <div>
          <Pagination
            v-model:limit="queryParams.pageSize"
            v-model:page="queryParams.pageNo"
            :total="total"
            @pagination="getList"
          />
        </div>
      </div>
      <div class="h-full flex flex-col justify-center" v-if="list.length == 0">
        <Empty />
      </div>
    </el-scrollbar>
    <!-- <PureTableBar title="" :columns="columns" @refresh="handleQuery">
      <template #default="{ size, dynamicColumns }">
        <pure-table
          ref="tableRef"
          row-key="id"
          align-whole="center"
          :loading="loading"
          :size="size"
          :data="list"
          :columns="dynamicColumns"
        >
          <template #name="scope">
            <div class="flex">
              <div>
                <el-image
                  :preview-teleported="true"
                  :src="scope.row.avatar"
                  class="w-[48px]! h-[48px]! m-r-10px rounded-4px align-middle"
                />
              </div>

              <el-text>{{ scope.row.name }}</el-text>
            </div>
          </template>
          <template #packageId="scope">
            <el-tag v-if="scope.row.packageId === 0" type="danger">系统商户</el-tag>
            <template v-else>
              <el-tag type="success">
                {{ scope.row.packageName }}
              </el-tag>
            </template>
          </template>
          <template #operation="scope">
            <div class="flex items-center justify-center">
              <el-button
                link
                type="primary"
                @click="openForm('update', scope.row.id)"
                v-hasPermi="['system:tenant:update']"
              >
                编辑
              </el-button>
              <el-button link type="primary" @click="handleAuthorized(scope.row)">
                关联商户
              </el-button>
              <el-button
                link
                type="danger"
                @click="handleDelete(scope.row.id)"
                v-hasPermi="['system:tenant:delete']"
              >
                删除
              </el-button>
              <el-button
                link
                type="warning"
                @click="handleUpdatePassword(scope.row)"
                v-hasPermi="['system:tenant:admin:update-password']"
              >
                重置密码
              </el-button>
            </div>
          </template>
          <template #empty>
            <Empty />
          </template>
        </pure-table>
        <Pagination
          v-model:limit="queryParams.pageSize"
          v-model:page="queryParams.pageNo"
          :total="total"
          @pagination="getList"
        />
      </template>
    </PureTableBar> -->
  </ContentWrap>
  <TenantSelectDialog @success="sumbitAuthorized" ref="tenantSelectRef" />
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import TenantSelectDialog from './components/tenantSelectDialog.vue'
import download from '@/utils/download'
import { formatDate } from '@/utils/formatTime'
import * as TenantApi from '@/api/system/tenant'
import * as TenantPackageApi from '@/api/system/tenantPackage'

import { defaultShortcuts } from '@/utils/formatTime'
/**时间范围限制 */
const disabledDate = (time: Date) => {
  return time.getTime() > Date.now()
}
// import { PureTableBar } from '@/components/RePureTableBar'
// const tableRef = ref()
// import { useTable } from './utils/hook'
// const { columns } = useTable()

defineOptions({ name: 'SystemTenant' })

const message = useMessage() // 消息弹窗
// const { t } = useI18n() // 国际化
const { push } = useRouter() // 路由跳转

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref<any>([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  contactName: undefined,
  contactMobile: undefined,
  status: undefined,
  createTime: [],
  cropName: undefined,
  tenantType: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const packageList = ref([] as TenantPackageApi.TenantPackageVO[]) //商户套餐列表

const handleTabClick = () => {
  nextTick(() => {
    handleQuery()
  })
}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await TenantApi.getTenantPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 查询租户列表 */
const tenantTypeList = ref()
const getTenantTypeList = async () => {
  const data = await TenantApi.getTenantTypeListByType()
  tenantTypeList.value = data
  queryParams.tenantType = data[0].value
}
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const openForm = (type: string, id?: number) => {
  if (type == 'update') {
    push({ name: 'TenantEdit', params: { id } })
    return
  }
  push({ name: 'TenantAdd' })
}

/** 删除按钮操作 */
// const handleDelete = async (id: number) => {
//   try {
//     // 删除的二次确认
//     await message.delConfirm()
//     // 发起删除
//     await TenantApi.deleteTenant(id)
//     message.success(t('common.delSuccess'))
//     // 刷新列表
//     await getList()
//   } catch {}
// }

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await TenantApi.exportTenant(queryParams)
    download.excel(data, '商户列表.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
/**重置密码操作 */
const handleUpdatePassword = async (row) => {
  try {
    // 重置密码的二次确认
    await message.confirm('是否重置管理员密码')
    // 发起重置
    let data = {
      id: row.id,
      contactMobile: row.contactMobile
    }
    await TenantApi.updatePasswordTenant(data)
    message.success('新密码已发送至管理员手机号')
    // 刷新列表
  } catch {}
}
/** 关联商户 */
const tenantSelectRef = ref()
const rowTenantId = ref()
const handleAuthorized = (row) => {
  rowTenantId.value = row.id
  tenantSelectRef.value.open(row.id, row.authorizedTenantCode)
}
const sumbitAuthorized = async (authorizedTenantCode) => {
  let authorizedArr = authorizedTenantCode.map((item) => {
    return item.id
  })
  let params = {
    id: rowTenantId.value,
    authorizedTenantCode: authorizedArr
  }
  await TenantApi.relationTenant(params)
  message.success('关联成功')

  await getList()
}
/** 初始化 **/
onMounted(async () => {
  await getList()
  await getTenantTypeList()
  packageList.value = await TenantPackageApi.getTenantPackageList()
})

onActivated(async () => {
  await getList()
  await getTenantTypeList()
  packageList.value = await TenantPackageApi.getTenantPackageList()
})
</script>
<style lang="scss" scoped>
.card-item {
  border: 1px solid transparent !important;
  &:hover {
    border: 1px solid var(--el-color-primary) !important;
    background: var(--el-color-primary-light-9) !important;
  }
}
</style>
